package com.cmcc.driver.ui.dialog

import android.text.InputFilter
import android.text.Spanned


/**
 *
 * @ProjectName:    Taxi Hailing
 * @Package:        com.cmcc.driver.ui.dialog
 * @ClassName:      PointLengthFilter
 * @Description:    Android EditText 限制输入小数位数
 * @Author:         wangyihao
 * @CreateDate:     2020/4/2 21:40
 * @UpdateUser:     更新者：
 * @UpdateDate:     2020/4/2 21:40
 * @UpdateRemark:   更新说明：
 * @Version:        1.0
 */
class PointLengthFilter : InputFilter {
    override fun filter(
        source: CharSequence, start: Int, end: Int,
        dest: Spanned, dstart: Int, dend: Int
    ): CharSequence? { // 删除等特殊字符，直接返回
        if ("" == source.toString()) {
            return null
        }
        val dValue = dest.toString()
        if (source != "." && !dValue.contains(".")) {
            val diff = dValue.length + 1 - INTEGER_DIGITS
            if (diff > 0) {
                return source.subSequence(start, end - diff)
            }
        } else {
            val splitArray = dValue.split(".").toTypedArray()
            if (splitArray.size > 1) {
                val dotValue = splitArray[1]
                val diff = dotValue.length + 1 - DECIMAL_DIGITS
                if (diff > 0) {
                    return source.subSequence(start, end - diff)
                }
            }else {
                return source.subSequence(start, end)
            }
        }
        return null
    }

    companion object {
        /** 输入框整数的位数  示例保留四位小数 */
        private const val INTEGER_DIGITS = 4

        /** 输入框小数的位数  示例保留两位小数 */
        private const val DECIMAL_DIGITS = 2
    }
}